package com.neusoft.bizcore.webauth.secret.ding;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

public class DingLoginConfigurer<T extends DingLoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {

    private final DingAuthenticationFilter authFilter;

    public DingLoginConfigurer() {
        this.authFilter = new DingAuthenticationFilter();
    }

    @Override
    public void configure(final B http) throws Exception {
        //设置Filter使用的AuthenticationManager,这里取公共的即可
        this.authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //不将认证后的context放入session
        this.authFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
        final DingAuthenticationFilter filter = this.postProcess(this.authFilter);
        //指定Filter的位置
        http.addFilterAfter(filter, LogoutFilter.class);
    }

    public DingLoginConfigurer<T, B> loginSuccessHandler(final AuthenticationSuccessHandler authSuccessHandler) {
        this.authFilter.setAuthenticationSuccessHandler(authSuccessHandler);
        return this;
    }

    public DingLoginConfigurer<T, B> loginFailureHandler(final AuthenticationFailureHandler authFailureHandler) {
        this.authFilter.setAuthenticationFailureHandler(authFailureHandler);
        return this;
    }

    public DingLoginConfigurer<T, B> loginProcessesUrl(final String processesUrl) {
        this.authFilter.setFilterProcessesUrl(processesUrl);
        return this;
    }
}
